﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'exercise_record_state.dart';
import 'exercise_record_detail_logic.dart';

/// 心率图表绘制器
class HeartRateChartPainter extends CustomPainter {
  final List<int> heartRates;

  HeartRateChartPainter(this.heartRates);

  @override
  void paint(Canvas canvas, Size size) {
    if (heartRates.isEmpty) return;

    // 过滤掉0值
    final validHr = heartRates.where((hr) => hr > 0).toList();
    if (validHr.isEmpty) return;

    final paint = Paint()
      ..color = Color(0xFFFF6B35)
      ..strokeWidth = 2
      ..style = PaintingStyle.stroke;

    final fillPaint = Paint()
      ..color = Color(0xFFFF6B35).withOpacity(0.2)
      ..style = PaintingStyle.fill;

    final maxHr = validHr.reduce((a, b) => a > b ? a : b).toDouble();
    final minHr = validHr.reduce((a, b) => a < b ? a : b).toDouble();
    final range = maxHr - minHr;

    if (range == 0) return;

    final path = Path();
    final fillPath = Path();
    
    fillPath.moveTo(0, size.height);

    for (int i = 0; i < validHr.length; i++) {
      final x = (i / (validHr.length - 1)) * size.width;
      final y = size.height - ((validHr[i] - minHr) / range) * size.height;

      if (i == 0) {
        path.moveTo(x, y);
        fillPath.lineTo(x, y);
      } else {
        path.lineTo(x, y);
        fillPath.lineTo(x, y);
      }
    }

    fillPath.lineTo(size.width, size.height);
    fillPath.close();

    canvas.drawPath(fillPath, fillPaint);
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

/// 运动记录详情页面
/// 显示单个运动记录的详细信息
class ExerciseRecordDetailView extends StatelessWidget {
  const ExerciseRecordDetailView({super.key});

  @override
  Widget build(BuildContext context) {
    // 获取 logic
    final logic = Get.find<ExerciseRecordDetailLogic>();
    final record = logic.record;
    
    return Scaffold(

      backgroundColor: Colors.black,
      appBar: AppBar(
        title: Text(
          record.trainingName,
          style: TextStyle(
            fontSize: 20.sp,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
          onPressed: () => Get.back(),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.info_outline, color: Colors.white),
            onPressed: () => _showAutoDetectionInfo(),
          ),
        ],
      ),
      body: SafeArea(
        child: Obx(() {
          // 显示 loading 状态
          if (logic.isLoadingDetail.value) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  CircularProgressIndicator(color: Colors.blue),
                  SizedBox(height: 16.h),
                  Text(
                    '正在加载锻炼详情...',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.grey[400],
                    ),
                  ),
                ],
              ),
            );
          }

          return SingleChildScrollView(
            padding: EdgeInsets.all(16.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(height: 20.h),
                
                // 时长（大字）
                _buildDurationSection(logic),
                SizedBox(height: 32.h),
                
                // 卡路里和平均心率
                _buildQuickStats(logic),
                SizedBox(height: 40.h),
                
                // 平均心率标题
                Text(
                  '平均心率',
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: Colors.grey[400],
                  ),
                ),
                SizedBox(height: 16.h),
                
                // 平均心率大字
                _buildAverageHeartRate(logic),
                SizedBox(height: 32.h),
                
                // 最大和最小心率
                _buildHeartRateRange(logic),
                SizedBox(height: 24.h),
                
                // 心率图表
                _buildHeartRateChart(logic),
                SizedBox(height: 16.h),
                
                // 开始和结束时间
                _buildTimeRange(logic),
                SizedBox(height: 40.h),
                
                // 心率区间
                _buildHeartRateZones(logic),
                SizedBox(height: 24.h),
              ],
            ),
          );
        }),
      ),
    );
  }

  /// 构建时长区域
  Widget _buildDurationSection(ExerciseRecordDetailLogic logic) {
    final duration = logic.exerciseDetail.value != null
        ? _parseDuration(logic.exerciseDetail.value!)
        : logic.record.duration;
    
    final hours = (duration / 3600).floor();
    final minutes = ((duration % 3600) / 60).floor();
    final seconds = duration % 60;
    
    return Text(
      '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}',
      style: TextStyle(
        fontSize: 48.sp,
        fontWeight: FontWeight.bold,
        color: Colors.white,
      ),
    );
  }

  /// 构建快速统计（卡路里和平均心率）
  Widget _buildQuickStats(ExerciseRecordDetailLogic logic) {
    final calories = logic.exerciseDetail.value != null
        ? _parseCalories(logic.exerciseDetail.value!)
        : logic.record.calories;
    
    final avgHeartRate = logic.exerciseDetail.value != null
        ? _parseAverageHeartRate(logic.exerciseDetail.value!)
        : logic.record.averageHeartRate ?? 0;
    
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        Column(
          children: [
            Row(
              children: [
                Icon(Icons.local_fire_department, color: Color(0xFFFF6B35), size: 20.sp),
                SizedBox(width: 4.w),
                Text(
                  '$calories千卡',
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                  ),
                ),
              ],
            ),
            SizedBox(height: 4.h),
            Text(
              '总消耗',
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.grey[400],
              ),
            ),
          ],
        ),
        Column(
          children: [
            Row(
              children: [
                Icon(Icons.favorite, color: Colors.red, size: 20.sp),
                SizedBox(width: 4.w),
                Text(
                  '$avgHeartRate BPM',
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                  ),
                ),
              ],
            ),
            SizedBox(height: 4.h),
            Text(
              '平均心率',
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.grey[400],
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建平均心率大字
  Widget _buildAverageHeartRate(ExerciseRecordDetailLogic logic) {
    final avgHeartRate = logic.exerciseDetail.value != null
        ? _parseAverageHeartRate(logic.exerciseDetail.value!)
        : logic.record.averageHeartRate ?? 0;
    
    return Column(
      children: [
        Text(
          '$avgHeartRate',
          style: TextStyle(
            fontSize: 72.sp,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
        Text(
          'BPM',
          style: TextStyle(
            fontSize: 16.sp,
            color: Colors.grey[400],
          ),
        ),
        SizedBox(height: 4.h),
        Text(
          'Avg HR',
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.grey[400],
          ),
        ),
      ],
    );
  }

  /// 构建心率范围（最大和最小）
  Widget _buildHeartRateRange(ExerciseRecordDetailLogic logic) {
    final hrData = _parseHeartRateData(logic.exerciseDetail.value);
    
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        Column(
          children: [
            Row(
              children: [
                Icon(Icons.circle, color: Color(0xFFFF6B35), size: 12.sp),
                SizedBox(width: 4.w),
                Text(
                  '${hrData['max']}',
                  style: TextStyle(
                    fontSize: 24.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
                Text(
                  ' BPM',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.grey[400],
                  ),
                ),
              ],
            ),
            SizedBox(height: 4.h),
            Text(
              'Max HR',
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.grey[400],
              ),
            ),
          ],
        ),
        Column(
          children: [
            Row(
              children: [
                Icon(Icons.circle, color: Color(0xFFFF6B35), size: 12.sp),
                SizedBox(width: 4.w),
                Text(
                  '${hrData['min']}',
                  style: TextStyle(
                    fontSize: 24.sp,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
                Text(
                  ' BPM',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.grey[400],
                  ),
                ),
              ],
            ),
            SizedBox(height: 4.h),
            Text(
              'Min HR',
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.grey[400],
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建心率图表
  Widget _buildHeartRateChart(ExerciseRecordDetailLogic logic) {
    final hrList = _parseHeartRateList(logic.exerciseDetail.value);
    
    if (hrList.isEmpty) {
      return Container(
        height: 150.h,
        alignment: Alignment.center,
        child: Text(
          '暂无心率数据',
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.grey[400],
          ),
        ),
      );
    }
    
    return Container(
      height: 150.h,
      width: double.infinity,
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      decoration: BoxDecoration(
        color: Colors.grey[900],
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: CustomPaint(
        painter: HeartRateChartPainter(hrList),
      ),
    );
  }

  /// 构建时间范围
  Widget _buildTimeRange(ExerciseRecordDetailLogic logic) {
    final record = logic.record;
    
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            '${record.startTime.month.toString().padLeft(2, '0')}/${record.startTime.day.toString().padLeft(2, '0')} ${record.startTime.hour.toString().padLeft(2, '0')}:${record.startTime.minute.toString().padLeft(2, '0')} 开始',
            style: TextStyle(
              fontSize: 12.sp,
              color: Colors.grey[400],
            ),
          ),
          Text(
            '${record.endTime.month.toString().padLeft(2, '0')}/${record.endTime.day.toString().padLeft(2, '0')} ${record.endTime.hour.toString().padLeft(2, '0')}:${record.endTime.minute.toString().padLeft(2, '0')} 结束',
            style: TextStyle(
              fontSize: 12.sp,
              color: Colors.grey[400],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建心率区间
  Widget _buildHeartRateZones(ExerciseRecordDetailLogic logic) {
    final zones = _calculateHeartRateZones(logic.exerciseDetail.value);
    
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: Colors.grey[900],
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '心率区间',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
              color: Colors.white,
            ),
          ),
          SizedBox(height: 20.h),
          
          // 总时长显示
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                '-- ',
                style: TextStyle(
                  fontSize: 32.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              Text(
                '小时 ',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.grey[400],
                ),
              ),
              Text(
                '-- ',
                style: TextStyle(
                  fontSize: 32.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              Text(
                '分钟',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.grey[400],
                ),
              ),
            ],
          ),
          SizedBox(height: 8.h),
          Center(
            child: Text(
              '总时长',
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.grey[400],
              ),
            ),
          ),
          SizedBox(height: 24.h),
          
          // 进度条
          Container(
            height: 8.h,
            decoration: BoxDecoration(
              color: Colors.grey[800],
              borderRadius: BorderRadius.circular(4.r),
            ),
          ),
          SizedBox(height: 20.h),
          
          // 各个心率区间
          _buildZoneRow('热身放松 (50%-60%)', zones['warmup'] ?? 0, Color(0xFF4CAF50)),
          SizedBox(height: 12.h),
          _buildZoneRow('脂肪燃烧 (60%-70%)', zones['fatBurn'] ?? 0, Color(0xFF8BC34A)),
          SizedBox(height: 12.h),
          _buildZoneRow('心肺强化 (70%-80%)', zones['cardio'] ?? 0, Color(0xFFFFC107)),
          SizedBox(height: 12.h),
          _buildZoneRow('耐力强化 (80%-90%)', zones['endurance'] ?? 0, Color(0xFFFF9800)),
          SizedBox(height: 12.h),
          _buildZoneRow('无氧极限 (90%-100%)', zones['peak'] ?? 0, Color(0xFFF44336)),
          SizedBox(height: 20.h),
          
          // 说明
          Container(
            padding: EdgeInsets.all(16.w),
            decoration: BoxDecoration(
              color: Colors.red.withOpacity(0.1),
              borderRadius: BorderRadius.circular(8.r),
              border: Border.all(color: Colors.red.withOpacity(0.3)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '心率区间',
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                    color: Colors.red[300],
                  ),
                ),
                SizedBox(height: 8.h),
                Text(
                  '静息心率：正常人在安静状态下每分钟心跳次数一般为60-100次。',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.grey[300],
                  ),
                ),
                SizedBox(height: 8.h),
                Text(
                  '运动心率：运动过程中根据心率区间可以判断身体的运动状态，选择合适的心率区间才能达到较好的运动效果。',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.grey[300],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建心率区间行
  Widget _buildZoneRow(String label, int minutes, Color color) {
    return Row(
      children: [
        Icon(Icons.circle, color: color, size: 12.sp),
        SizedBox(width: 8.w),
        Expanded(
          child: Text(
            label,
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.white,
            ),
          ),
        ),
        Text(
          '0 小时 ${minutes.toString().padLeft(2, '0')} 分钟',
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.grey[400],
          ),
        ),
      ],
    );
  }

  // 辅助方法
  int _parseDuration(Map<String, dynamic> detail) {
    final rawData = detail['rawData'] as String? ?? '';
    final validTimeMatch = RegExp(r'validTime=(\d+)').firstMatch(rawData);
    return validTimeMatch != null ? int.parse(validTimeMatch.group(1)!) : 0;
  }

  int _parseCalories(Map<String, dynamic> detail) {
    final rawData = detail['rawData'] as String? ?? '';
    final caloriesMatch = RegExp(r'calories=(\d+)').firstMatch(rawData);
    return caloriesMatch != null ? int.parse(caloriesMatch.group(1)!) : 0;
  }

  int _parseAverageHeartRate(Map<String, dynamic> detail) {
    final hrList = _parseHeartRateList(detail);
    if (hrList.isEmpty) return 0;
    
    final validHr = hrList.where((hr) => hr > 0).toList();
    if (validHr.isEmpty) return 0;
    
    return (validHr.reduce((a, b) => a + b) / validHr.length).round();
  }

  List<int> _parseHeartRateList(Map<String, dynamic>? detail) {
    if (detail == null) return [];
    
    final rawData = detail['rawData'] as String? ?? '';
    final hrListMatch = RegExp(r'hrList=\[([\d,\s]+)\]').firstMatch(rawData);
    
    if (hrListMatch != null) {
      final hrListStr = hrListMatch.group(1)!;
      return hrListStr
          .split(',')
          .map((s) => int.tryParse(s.trim()) ?? 0)
          .toList();
    }
    
    return [];
  }

  Map<String, int> _parseHeartRateData(Map<String, dynamic>? detail) {
    final hrList = _parseHeartRateList(detail);
    final validHr = hrList.where((hr) => hr > 0).toList();
    
    if (validHr.isEmpty) {
      return {'max': 0, 'min': 0};
    }
    
    return {
      'max': validHr.reduce((a, b) => a > b ? a : b),
      'min': validHr.reduce((a, b) => a < b ? a : b),
    };
  }

  Map<String, int> _calculateHeartRateZones(Map<String, dynamic>? detail) {
    // 这里应该根据实际心率数据计算各个区间的时长
    // 暂时返回0
    return {
      'warmup': 0,
      'fatBurn': 0,
      'cardio': 0,
      'endurance': 0,
      'peak': 0,
    };
  }

  /// 构建自动检测标签区域
  Widget _buildAutoDetectionSection(HistoryTrainingRecord record) {
    return Row(
      children: [
        Text(
          '运动自动检测',
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.grey[400],
          ),
        ),
        SizedBox(width: 8.w),
        GestureDetector(
          onTap: () => _showAutoDetectionInfo(),
          child: Icon(
            Icons.info_outline,
            size: 16.sp,
            color: Colors.grey[400],
          ),
        ),
      ],
    );
  }

  /// 构建主要信息区域
  Widget _buildMainInfoSection(HistoryTrainingRecord record) {
    return Column(
      children: [
        // 日期
        Text(
          '${record.startTime.day.toString().padLeft(2, '0')} ${_getMonthName(record.startTime.month)}. ${record.startTime.year}',
          style: TextStyle(
            fontSize: 16.sp,
            color: Colors.grey[400],
          ),
        ),
        SizedBox(height: 16.h),
        
        // 主要时长
        Text(
          '${(record.duration / 60).round()} 分钟',
          style: TextStyle(
            fontSize: 48.sp,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
      ],
    );
  }

  /// 构建统计信息区域
  Widget _buildStatisticsSection(HistoryTrainingRecord record) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 20.h),
      decoration: BoxDecoration(
        border: Border(
          top: BorderSide(color: Colors.grey[800]!, width: 1),
          bottom: BorderSide(color: Colors.grey[800]!, width: 1),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          // 卡路里
          _buildStatItem(
            '${record.calories}',
            '卡路里',
            Icons.local_fire_department,
            const Color(0xFFFF6B35),
          ),
          
          // 时间范围
          _buildStatItem(
            '${record.startTime.hour.toString().padLeft(2, '0')}:${record.startTime.minute.toString().padLeft(2, '0')}-${record.endTime.hour.toString().padLeft(2, '0')}:${record.endTime.minute.toString().padLeft(2, '0')}',
            '时长',
            Icons.access_time,
            Colors.blue,
          ),
          
          // 强度
          _buildStatItem(
            _getIntensityText(record.calories, record.duration),
            '强度',
            Icons.trending_up,
            Colors.green,
          ),
        ],
      ),
    );
  }

  /// 构建时间信息区域
  Widget _buildTimeSection(HistoryTrainingRecord record) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '详细信息',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        SizedBox(height: 16.h),
        
        Container(
          padding: EdgeInsets.all(16.w),
          decoration: BoxDecoration(
            color: Colors.grey[900],
            borderRadius: BorderRadius.circular(12.r),
          ),
          child: Column(
            children: [
              _buildDetailRow('开始时间', '${record.startTime.hour.toString().padLeft(2, '0')}:${record.startTime.minute.toString().padLeft(2, '0')}'),
              SizedBox(height: 12.h),
              _buildDetailRow('结束时间', '${record.endTime.hour.toString().padLeft(2, '0')}:${record.endTime.minute.toString().padLeft(2, '0')}'),
              SizedBox(height: 12.h),
              _buildDetailRow('训练时长', '${(record.duration / 60).round()}分钟'),
              SizedBox(height: 12.h),
              _buildDetailRow('消耗卡路里', '${record.calories}千卡'),
              if (record.distance != null) ...[
                SizedBox(height: 12.h),
                _buildDetailRow('运动距离', '${record.distance!.toStringAsFixed(1)}公里'),
              ],
              if (record.averageHeartRate != null) ...[
                SizedBox(height: 12.h),
                _buildDetailRow('平均心率', '${record.averageHeartRate}BPM'),
              ],
              if (record.maxHeartRate != null) ...[
                SizedBox(height: 12.h),
                _buildDetailRow('最大心率', '${record.maxHeartRate}BPM'),
              ],
            ],
          ),
        ),
      ],
    );
  }

  /// 构建动作详情区域
  Widget _buildActionDetailsSection(HistoryTrainingRecord record) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '动作详情',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        SizedBox(height: 16.h),
        
        Container(
          padding: EdgeInsets.all(16.w),
          decoration: BoxDecoration(
            color: Colors.grey[900],
            borderRadius: BorderRadius.circular(12.r),
          ),
          child: Column(
            children: record.actionDetails.map((action) => Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      action.actionName,
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                      ),
                    ),
                    Text(
                      '${(action.duration / 60).round()}分钟',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[400],
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 8.h),
                Row(
                  children: [
                    Text(
                      '卡路里: ${action.calories}千卡',
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: Colors.grey[400],
                      ),
                    ),
                    if (action.heartRate != null) ...[
                      SizedBox(width: 16.w),
                      Text(
                        '心率: ${action.heartRate}BPM',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colors.grey[400],
                        ),
                      ),
                    ],
                    if (action.distance != null) ...[
                      SizedBox(width: 16.w),
                      Text(
                        '距离: ${action.distance!.toStringAsFixed(1)}公里',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colors.grey[400],
                        ),
                      ),
                    ],
                  ],
                ),
                if (record.actionDetails.last != action) ...[
                  SizedBox(height: 16.h),
                  Divider(color: Colors.grey[800]),
                  SizedBox(height: 16.h),
                ],
              ],
            )).toList(),
          ),
        ),
      ],
    );
  }

  /// 构建统计项
  Widget _buildStatItem(String value, String label, IconData icon, Color color) {
    return Column(
      children: [
        Icon(icon, color: color, size: 20.sp),
        SizedBox(height: 8.h),
        Text(
          value,
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        SizedBox(height: 4.h),
        Text(
          label,
          style: TextStyle(
            fontSize: 12.sp,
            color: Colors.grey[400],
          ),
        ),
      ],
    );
  }

  /// 构建详情行
  Widget _buildDetailRow(String label, String value) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.grey[400],
          ),
        ),
        Text(
          value,
          style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
      ],
    );
  }

  /// 获取月份名称
  String _getMonthName(int month) {
    const months = [
      '1月', '2月', '3月', '4月', '5月', '6月',
      '7月', '8月', '9月', '10月', '11月', '12月'
    ];
    return months[month - 1];
  }

  /// 获取强度文本
  String _getIntensityText(int calories, int duration) {
    final intensity = calories / (duration / 60); // 每分钟卡路里
    if (intensity < 5) return '低';
    if (intensity < 10) return '中';
    return '高';
  }

  /// 显示自动检测信息
  void _showAutoDetectionInfo() {
    Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Container(
          padding: EdgeInsets.all(20.w),
          decoration: BoxDecoration(
            color: Colors.grey[900],
            borderRadius: BorderRadius.circular(16.r),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '关于运动自动检测',
                    style: TextStyle(
                      fontSize: 18.sp,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                  IconButton(
                    icon: const Icon(Icons.close, color: Colors.white),
                    onPressed: () => Get.back(),
                  ),
                ],
              ),
              SizedBox(height: 16.h),
              Text(
                '锻炼检测将评估您的活动水平、确定锻炼类型并计算您的卡路里消耗。',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.grey[300],
                ),
              ),
              SizedBox(height: 12.h),
              Text(
                '持续时间少于10分钟的活动将不会被自动识别。',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.grey[300],
                ),
              ),
              SizedBox(height: 12.h),
              Text(
                '您可以选择自定义锻炼的持续时间和类型。',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.grey[300],
                ),
              ),
            ],
          ),
        ),
      ),
      barrierDismissible: true,
    );
  }
}
